package com.findmeastore.action;

import java.util.ArrayList;
import java.util.List;

import com.findmeastore.bc.ICategoryBc;
import com.findmeastore.bc.IProductBc;
import com.findmeastore.bo.CategoryBo;
import com.findmeastore.bo.ProductBo;
import com.findmeastore.dto.ProductDto;

public class ProductCrudAction {
	private Integer id;
	private ProductDto productDto;
	private IProductBc productBc;
	private ICategoryBc categoryBc;
	private List<ProductBo> products;
	private List<CategoryBo> categories;
	private String action;

	public String execute() {
		if ("save".equals(action)) {
			return save();
		} else if ("list".equals(action)) {
			return list();
		} else if ("edit".equals(action)) {
			return edit();
		}
		return list();
	}

	public String list() {
		setProducts(productBc.getAllProducts());
		return "LIST";
	}

	public String edit() {
		if (id != null && id > 0) {
			ProductBo productBo = productBc.getProductById(id);
			if (productBo != null) {
				productDto = new ProductDto();
				productDto.setId(id);
				productDto.setName(productBo.getName());
				List<Integer> categoryIds = new ArrayList<Integer>();
				for(CategoryBo categoryBo:productBo.getCategories()){
					categoryIds.add(categoryBo.getId());
				}
				productDto.setCategoryIds(categoryIds.toArray(new Integer[]{}));
			}
		}
		setCategories(categoryBc.getAllCategories());
		return "EDIT";
	}

	public String save() {
		if (productDto.getId() == null) {
			productDto.setCreatedById(1);
		}
		productDto.setModifiedById(1);
		productBc.saveProduct(productDto);
		return "REDIRECT";
	}

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public List<ProductBo> getProducts() {
		return products;
	}

	public void setProducts(List<ProductBo> products) {
		this.products = products;
	}

	public ProductDto getProductDto() {
		return productDto;
	}

	public void setProductDto(ProductDto productDto) {
		this.productDto = productDto;
	}

	public IProductBc getProductBc() {
		return productBc;
	}

	public void setProductBc(IProductBc productBc) {
		this.productBc = productBc;
	}

	public List<CategoryBo> getCategories() {
		return categories;
	}

	public void setCategories(List<CategoryBo> categories) {
		this.categories = categories;
	}

	public ICategoryBc getCategoryBc() {
		return categoryBc;
	}

	public void setCategoryBc(ICategoryBc categoryBc) {
		this.categoryBc = categoryBc;
	}
}
